package sc.tool.sqlgen.branchinfo.fos;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import sc.common.test.ListUtil;
import sc.prototype.common.ConsoleUtil;
import sc.tool.sqlgen.branchinfo.BranchInfo;
import sc.tool.sqlgen.branchinfo.CreateSheet;
import sc.tool.sqlgen.branchinfo.ICBCParser;
import sc.tool.sqlgen.branchinfo.ParseResult;
import sc.tool.sqlgen.branchinfo.XlsxUtil;

public class BranchUpdateProcessor implements ConsoleUtil {

    String latestFilePath = "D:/WeibopayMemo/出款服务FOS/联行号信息.xml";
    String currentFilePath = "D:/WeibopayMemo/出款服务FOS/fos.xlsx";
    String outputFilePath = "D:/WeibopayMemo/出款服务FOS/fos_update_20130115_raw.xlsx";

    HashMap<String, BranchInfo> parseLatest() {
        ParseResult rst = new ICBCParser().parse(new File(latestFilePath));
        Console.info("最新文件解析完成");
        if (rst.getFailResults().size() != 0) {
            ListUtil.print("解析错误", rst.getFailResults().keySet(), 3);
            return null;
        } else {
            ListUtil.print("解析成功", rst.getSuccessResults(), 3);
            HashMap<String, BranchInfo> ret = new HashMap<String, BranchInfo>();
            for (BranchInfo branch : rst.getSuccessResults()) {
                ret.put(branch.getBranchId(), branch);
            }
            return ret;
        }
    }

    List<BranchInfo> parseCurrent() {
        List<BranchInfo> ret = new LinkedList<BranchInfo>();
        List<String[]> list = XlsxUtil.loadItems(currentFilePath, 1, "SQL Results", "SQL Results (1)");
        parse(ret, list);
        ListUtil.print("数据库文件解析", ret, 3);
        return ret;
    }

    void parse(List<BranchInfo> branches, List<String[]> infos) {
        for (String[] info : infos) {
            branches.add(parse(info));
        }
    }

    BranchInfo parse(String[] info) {
        BranchInfo ret = new BranchInfo();
        ret.setId(Long.parseLong(info[1]));
        ret.setBranchId(info[2]);
        ret.setBranchName(info[3]);
        ret.setAliasNames(info[4]);
        ret.setUnifiedBankId(info[5]);
        ret.setBankCode(info[6]);
        ret.setProvId(info[7]);
        ret.setCityId(info[8]);
        ret.setEnableFlag(info[10]);
        ret.setMemo(info[13]);
        return ret;
    }

    public void process() {
        //1 最新分支行文件解析
        HashMap<String, BranchInfo> latests = parseLatest();
        List<BranchInfo> currents = parseCurrent();
        List<BranchInfo> deletes = new ArrayList<BranchInfo>();
        List<BranchChange> updates = new ArrayList<BranchChange>();
        BranchInfo cur = null, lat = null;
        BranchChange change = null;
        int sameCount = 0;
        for (Iterator<BranchInfo> curIt = currents.iterator(); curIt.hasNext();) {
            cur = curIt.next();
            lat = latests.get(cur.getBranchId());
            if (lat == null) {
                //最新不存在，应该删除
                deletes.add(cur);
                curIt.remove();
            } else {
                //最新存在，比较
                change = null;
                if (!StringUtils.equals(lat.getBranchName(), cur.getBranchName())) {
                    if (change == null) {
                        change = new BranchChange(cur, lat);
                    }
                    change.addDiff("branchName");
                }
                if (!StringUtils.equals(lat.getUnifiedBankId(), cur.getUnifiedBankId())) {
                    if (change == null) {
                        change = new BranchChange(cur, lat);
                    }
                    change.addDiff("unifiedBankId");
                }
                if (!StringUtils.equals(lat.getBankCode(), cur.getBankCode())) {
                    if (change == null) {
                        change = new BranchChange(cur, lat);
                    }
                    change.addDiff("bankCode");
                }
                if (!StringUtils.equals(lat.getProvId(), cur.getProvId())) {
                    if (change == null) {
                        change = new BranchChange(cur, lat);
                    }
                    change.addDiff("provId");
                }
                if (!StringUtils.equals(lat.getCityId(), cur.getCityId())) {
                    if (change == null) {
                        change = new BranchChange(cur, lat);
                    }
                    change.addDiff("cityId");
                }
                if (change != null) {
                    updates.add(change);
                } else {
                    sameCount++;
                }
                curIt.remove();
                latests.remove(cur.getBranchId());
            }
        }
        Collection<BranchInfo> inserts = latests.values();
        Console.info("比对结束，相同：{}", sameCount);
        ListUtil.print("新增", inserts, 5);
        ListUtil.print("更新", updates, 5);
        ListUtil.print("删除", deletes, 5);
        XlsxUtil.writeFile(outputFilePath, createSheets(inserts, updates, deletes));
        Console.info("明细以输出到：{}", outputFilePath);
    }

    public List<CreateSheet> createSheets(Collection<BranchInfo> inserts, Collection<BranchChange> updates,
            Collection<BranchInfo> deletes) {
        List<CreateSheet> ret = new ArrayList<CreateSheet>();

        List<String[]> sheet = new ArrayList<String[]>();
        CreateSheet create = new CreateSheet("新增", sheet);
        sheet.add(new String[] { "联行号", "分支行名称", "分支行简称", "行别代码", "银行编码", "省份Id", "城市Id" });
        ret.add(create);
        for (BranchInfo b : inserts) {
            sheet.add(new String[] { b.getBranchId(), b.getBranchName(), "", b.getUnifiedBankId(), b.getBankCode(),
                    b.getProvId(), b.getCityId() });
        }

        sheet = new ArrayList<String[]>();
        create = new CreateSheet("更新", sheet);
        sheet.add(new String[] { "区别描述", "区别数量", "联行号", "旧名称", "新名称", "现有信息", "最新信息" });
        ret.add(create);
        for (BranchChange b : updates) {
            sheet.add(new String[] { b.diffDesc, Integer.toString(b.diffCount), b.old.getBranchId(),
                    b.old.getBranchName(), b.latest.getBranchName(), b.old.toString(), b.latest.toString() });
        }

        sheet = new ArrayList<String[]>();
        create = new CreateSheet("删除", sheet);
        sheet.add(new String[] { "联行号", "分支行名称", "分支行简称", "行别代码", "银行编码", "省份Id", "城市Id", "启用", "备注" });
        ret.add(create);
        for (BranchInfo b : deletes) {
            sheet.add(new String[] { b.getBranchId(), b.getBranchName(), b.getAliasNames(), b.getUnifiedBankId(),
                    b.getBankCode(), b.getProvId(), b.getCityId(), b.getEnableFlag(), b.getMemo() });
        }

        return ret;
    }

    public static void main(String[] args) {
        new BranchUpdateProcessor().process();
    }
}
